
import json
import requests

class ImageService:
    def __init__(self):
        pass

class ImageServiceBaidu(ImageService):
    def __init__(self):
        with open('config/config_request_baidu.json', 'r') as file:
            self.content = file.read()
            file.close()
        print("content: ", self.content)
        conf_data = json.loads(self.content)
        self.req_url = conf_data['url']
        self.req_key = conf_data['key']
        self.req_secret = conf_data['sec']
        self.req_token = ""

    def detect_obj(self, image):
        self.get_token_key()
        req_data = {"image":image}
        if image.startswith('http'):
            print("this is http request")
            req_data = {"url":image}

        req_data["scenes"] = ["advanced_general", "multi_object_detect", "animal", "plant"]
        res = requests.request("POST", self.req_url+"?access_token="+self.req_token,
                         headers={"Content-Type": "application/json;charset=utf-8"},
                         data=json.dumps(req_data))
        self.response = json.loads(res.content)
        if 'result' not in self.response:
            print("Error: ", res.content)
        return self.response

    def get_token_key(self):
        if (self.req_token == ""):
            print("do token request")
            url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + self.req_key + "&client_secret=" + self.req_secret

            payload = ""
            headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

            response = requests.request("POST", url, headers=headers, data=payload)

            res = json.loads(response.text)

            self.req_token = res["access_token"]
        return self.req_token


def createImageService(service_id = 1):
    if (service_id == 1):
        service = ImageServiceBaidu()
        return service
    return None
